#!/bin/bash

set +x

LOG_PATH=/app/oem/ai/positec/robot_logs/
LOG_NAME=sys.log
LOG_MAX_MB=1
INTERVAL=1
process1=("viwo_node" "pose_graph_optimization_node" "dr_odo" "seg_ros" "det_ros" "objectcluster/objseg_gridclass" "segfusion_node" "slope" "bboxmerge" "zvision_lidar_pointcloud/CloudNodelet" "lib/serial_date/serial_date" "camera_pub" "__name:=realsense2_camera_manager")

disp_date(){
	printf "%s\t" `date "+%D-%T"`	
}


disp_mem(){
	MEM=`cat /proc/meminfo | grep MemTotal | awk -F" " '{print $2}'`
	SWAP=`cat /proc/meminfo | grep SwapTotal | awk -F" " '{print $2}'`
	MEM_F=`cat /proc/meminfo | grep MemFree | awk 'NR==1 {print $2}'`
	SWAP_F=`cat /proc/meminfo | grep SwapFree | awk '{print $2}'`
	MEM=`expr $(($MEM+$SWAP)) / 1024`
	MEM_F=`expr $(($MEM_F+$SWAP_F)) / 1024`
	MEM_U=`expr $(($MEM-$MEM_F)) `
	MEM_10=`expr $(($MEM_U*100/$MEM)) `
	printf "%s/%sMB (%.1f%%)\t"  $MEM_U $MEM $MEM_10
}

disp_storage(){
	df -h | awk '$NF=="/" {printf "%.1f/%.1fGB (%s)\t", $3,$2,$5}'
}

disp_cpu(){
	#uptime | awk '{printf "%.2f/%s\t", $9, '`nproc`'}'
	top -b -i -c -n5 -d.2 | grep "Cpu" | tail -n1 | awk '{printf "%.1f%%\t", 100-$(NF-9)}'
}

disp_func(){
	for ((i=0;i<${#process1[*]};i++))
 	 do
       		cpu_r=`ps aux  | grep ${process1[i]} | grep -v grep `
       		if [[ $cpu_r = "" ]]; then
           		printf "%.1f%%\t" 0.0
      		else
			ps aux  | grep ${process1[i]} | grep -v grep | awk -F" " 'NR==1 {printf "%.1f%%\t", $3}'
      		fi
  	done
        
}

echo_banner(){
	printf "Time\t\t\tMem\t\t\tStorage\t\t\tUsage\tviw\tPsfusn\tdr_od\tSeg\tDet\tObjec\tSegfu\tSlope\tBbox\tlidar\tUsb\tCamr\tRelses\t\n"
}

check_size(){
	size=`ls -l ${LOG_PATH}/${LOG_NAME} | awk '{ print $5 }' `
	limit=`expr $LOG_MAX_MB \* 1024 \* 1024`
	if [ ${size} -gt ${limit} ]; then
		echo "LOG FILE EXCEED MAX SIZE"
		rm -rf ${LOG_PATH}/${LOG_NAME}
		sync
	fi
}

disp_info()
{
	disp_date
	disp_mem
	disp_storage
	disp_cpu
        disp_func
	echo
}

once=1

echo "$0 PID:$$"
while true
do
	if [ ! -f ${LOG_PATH}/${LOG_NAME} ]; then
		echo_banner 1>${LOG_PATH}/${LOG_NAME}
	fi
	if [ $once == 1 ];then
		printf "\n" 1>>${LOG_PATH}/${LOG_NAME}
		once=0
	fi
	
	sleep ${INTERVAL}
	disp_info 1>>${LOG_PATH}/${LOG_NAME}
	check_size
done

